<template>
  <div class="order-confirm-container">
    <!-- 顶部导航 -->
    <el-header class="order-header">
      <div class="header-back" @click="router.back()">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">确认订单</div>
    </el-header>

    <!-- 收货地址 -->
    <div class="address-section" @click="showAddressDialog = true">
      <div class="address-info">
        <el-icon><Location /></el-icon>
        <div class="address-details">
          <div class="receiver">
            <span>{{ selectedAddress.username || userInfo.username }}</span>
            <span>{{ selectedAddress.phone || userInfo.phone }}</span>
          </div>
          <div class="address">{{ selectedAddress.address || userInfo.address }}</div>
        </div>
      </div>
      <el-icon><ArrowRight /></el-icon>
    </div>

    <!-- 地址管理对话框 -->
    <el-dialog v-model="showAddressDialog" title="收货地址" width="90%">
      <div class="address-list">
        <!-- 当前地址（从cookie获取） -->
        <div class="current-address-title">当前地址</div>
        <div 
          class="address-item current"
          :class="{ 'selected': selectedAddress.id === 'current' }"
          @click="selectCurrentAddress"
        >
          <div class="address-content">
            <div class="receiver">
              <span>{{ userInfo.username }}</span>
              <span>{{ userInfo.phone }}</span>
            </div>
            <div class="address-text">{{ userInfo.address }}</div>
          </div>
        </div>

        <!-- 历史地址 -->
        <div class="history-address-title" v-if="addressList.length > 0">历史地址</div>
        <div 
          v-for="address in addressList" 
          :key="address.id" 
          class="address-item"
          :class="{ 'selected': selectedAddress.id === address.id }"
          @click="selectAddress(address)"
        >
          <div class="address-content">
            <div class="receiver">
              <span>{{ userInfo.username }}</span>
              <span>{{ address.phone }}</span>
            </div>
            <div class="address-text">{{ address.address }}</div>
          </div>
          <el-button 
            type="danger" 
            size="small" 
            @click.stop="deleteAddress(address.id)"
            :icon="Delete"
            circle
          />
        </div>
        
        <!-- 添加新地址 -->
        <div class="add-address">
          <el-form :model="newAddress" label-width="80px">
            <el-form-item label="手机号" required>
              <el-input 
                v-model="newAddress.phone" 
                placeholder="请输入手机号"
                maxlength="11"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="收货地址" required>
              <el-input 
                v-model="newAddress.address" 
                placeholder="请输入详细地址" 
                type="textarea"
                rows="2"
              />
            </el-form-item>
            <el-form-item>
              <el-button 
                type="primary" 
                @click="createAddress"
                :loading="creatingAddress"
                :icon="CirclePlus"
              >
                添加新地址
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>

    <!-- 订单商品列表 -->
    <div class="order-items">
      <div class="merchant-info">
        <img :src="getImageUrl(merchant.avatar_path)" class="merchant-avatar">
        <span class="merchant-name">{{ merchant.name }}</span>
      </div>

      <div class="item-list">
        <div v-for="item in selectedFoods" :key="item.dishId" class="order-item">
          <div class="item-name">{{ item.name }}</div>
          <div class="item-quantity">x{{ item.count }}</div>
          <div class="item-price">¥{{ (item.price * item.count).toFixed(2) }}</div>
        </div>
      </div>
    </div>

    <!-- 订单费用明细 -->
    <div class="order-summary">
      <div class="summary-row">
        <span>商品总价</span>
        <span>¥{{ subtotal.toFixed(2) }}</span>
      </div>
      <div class="summary-row">
        <span>配送费</span>
        <span>¥{{ deliveryFee.toFixed(2) }}</span>
      </div>
      <div class="summary-row total">
        <span>实付款</span>
        <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-method">
      <div class="payment-title">支付方式</div>
      <div class="payment-option">
        <img :src="alipayIcon" class="alipay-icon">
        <span>支付宝支付</span>
        <el-radio v-model="paymentMethod" label="alipay" />
      </div>
    </div>

    <!-- 提交订单按钮 -->
    <div class="submit-order">
      <el-button 
        type="primary" 
        class="pay-btn" 
        :loading="loading"
        @click="handlePayment"
        :disabled="!hasSelectedAddress || isPaying"
      >
        {{ isPaying ? '支付处理中...' : `去支付 ¥${totalPrice.toFixed(2)}` }}
      </el-button>
    </div>

    <!-- 支付状态弹窗 -->
    <el-dialog 
      v-model="showPaymentDialog" 
      title="支付处理中" 
      width="90%" 
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="payment-status">
        <el-icon class="loading-icon" v-if="paymentStatus === 'pending'"><Loading /></el-icon>
        <el-icon class="success-icon" v-else-if="paymentStatus === 'success'"><Select /></el-icon>
        <el-icon class="error-icon" v-else><Close /></el-icon>
        <div class="status-text">
          {{ statusMessages[paymentStatus] }}
        </div>
        <el-button 
          type="primary" 
          v-if="paymentStatus !== 'pending'" 
          @click="handlePaymentResult"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  ArrowLeft, 
  Location, 
  ArrowRight,
  CirclePlus,
  Delete,
  Loading,
  Select,
  Close
} from '@element-plus/icons-vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import { useCookies } from 'vue3-cookies';
import { ElMessage } from 'element-plus';

const { cookies } = useCookies();
const router = useRouter();
const route = useRoute();

// 导入图片
import defaultMerchantImage from '@/assets/default-merchant.jpg';
import alipayIcon from '@/assets/alipay.png';

// 支付相关状态
const loading = ref(false);
const isPaying = ref(false);
const showPaymentDialog = ref(false);
const paymentStatus = ref('pending'); // pending/success/failed
const paymentPolling = ref(null);
const orderId = ref(null);

const statusMessages = {
  pending: '正在等待支付完成...',
  success: '支付成功！即将返回首页',
  failed: '支付失败，请重新尝试'
};

// 地址相关状态
const showAddressDialog = ref(false);
const addressList = ref([]);
const selectedAddress = ref({
  id: 'current', // 默认使用当前地址
  phone: '',
  address: '',
  username: ''
});
const newAddress = ref({
  phone: '',
  address: ''
});
const creatingAddress = ref(false);

// 从路由参数获取数据
const merchant = ref({
  merchantId: route.params.merchantId,
  name: route.query.merchantName,
  avatar_path: route.query.merchantAvatar
});

const deliveryFee = ref(parseFloat(route.query.deliveryFee) || 0);
const selectedFoods = ref(JSON.parse(route.query.selectedFoods || '[]'));

// 用户信息（优先从cookie获取）
const userInfo = ref({
  userId: cookies.get('userId'),
  username: cookies.get('username') || '未设置',
  phone: cookies.get('phone') || '未设置',
  address: cookies.get('address') || '请选择收货地址'
});

// 计算属性
const subtotal = computed(() => {
  return selectedFoods.value.reduce((sum, item) => sum + (item.price * item.count), 0);
});

const totalPrice = computed(() => {
  return subtotal.value + deliveryFee.value;
});

const hasSelectedAddress = computed(() => {
  return (selectedAddress.value.id === 'current' && userInfo.value.address) || 
         (selectedAddress.value.id && selectedAddress.value.address);
});

// 获取图片完整URL
const getImageUrl = (path) => {
  if (!path) return defaultMerchantImage;
  return `${import.meta.env.VITE_API_BASE_URL}${path}`;
};

// 地址管理功能
const fetchAddressList = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/address/getaddress`, null, {
      params: {
        userid: userInfo.value.userId
      }
    });
    
    if (Array.isArray(response.data)) {
      addressList.value = response.data;
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
  }
};

const selectCurrentAddress = () => {
  selectedAddress.value = {
    id: 'current',
    phone: userInfo.value.phone,
    address: userInfo.value.address,
    username: userInfo.value.username
  };
  showAddressDialog.value = false;
};

const selectAddress = (address) => {
  selectedAddress.value = {
    id: address.id,
    phone: address.phone,
    address: address.address,
    username: userInfo.value.username
  };
  showAddressDialog.value = false;
};

const createAddress = async () => {
  if (!newAddress.value.phone || !newAddress.value.address) {
    ElMessage.warning('请填写完整的地址信息');
    return;
  }

  if (!/^1[3-9]\d{9}$/.test(newAddress.value.phone)) {
    ElMessage.warning('请输入正确的手机号');
    return;
  }

  try {
    creatingAddress.value = true;
    const response = await axios.post(`${API_BASE_URL}/address/usercreateaddress`, null, {
      params: {
        userid: userInfo.value.userId,
        phone: newAddress.value.phone,
        address: newAddress.value.address
      }
    });

    if (response.data === 'OK') {
      ElMessage.success('地址添加成功');
      newAddress.value = { phone: '', address: '' };
      await fetchAddressList();
    } else {
      ElMessage.error('地址添加失败');
    }
  } catch (error) {
    ElMessage.error('地址添加失败');
    console.error('添加地址失败:', error);
  } finally {
    creatingAddress.value = false;
  }
};

const deleteAddress = async (id) => {
  try {
    const response = await axios.post(`${API_BASE_URL}/address/deleteaddress`, null, {
      params: { id }
    });

    if (response.data === 'success') {
      ElMessage.success('地址删除成功');
      if (selectedAddress.value.id === id) {
        selectCurrentAddress();
      }
      await fetchAddressList();
    } else {
      ElMessage.error('地址删除失败');
    }
  } catch (error) {
    ElMessage.error('地址删除失败');
    console.error('删除地址失败:', error);
  }
};

// 订单创建与支付
const handlePayment = async () => {
  if (!hasSelectedAddress.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  try {
    loading.value = true;
    isPaying.value = true;
    
    // 1. 创建订单
    const orderResponse = await axios.post(`${API_BASE_URL}/order/createorder`, {
      userId: userInfo.value.userId,
      merchantId: merchant.value.merchantId,
      username: userInfo.value.username,
      phone: selectedAddress.value.phone,
      address: selectedAddress.value.address,
      deliveryfee:deliveryFee.value,
      items: selectedFoods.value.map(item => ({
        dishId: item.dishId,
        quantity: item.count,
        // price: item.price
      }))
    });

    // 2. 处理创建订单的响应
    if (typeof orderResponse.data === 'number') {
      if (orderResponse.data === 0) {
        ElMessage.warning('您在该商户已有未支付订单！');
        return;
      } else {
        orderId.value = orderResponse.data;
      }
    } else {
      ElMessage.error('创建订单失败');
      return;
    }

    // 3. 调用支付接口
    const payResponse = await axios.post(`${API_BASE_URL}/pay/userpay?orderId=${orderId.value}`, null, {
      responseType: 'text/html'
    });

    // 4. 打开支付窗口
    const payWindow = window.open('', '_blank');
    payWindow.document.write(payResponse.data);
    payWindow.document.close();
    
    // 5. 显示支付状态弹窗
    showPaymentDialog.value = true;
    paymentStatus.value = 'pending';
    
    // 6. 开始轮询订单状态
    startPaymentPolling();

    // 7. 监听支付窗口关闭
    const checkInterval = setInterval(() => {
      if (payWindow.closed) {
        clearInterval(checkInterval);
      }
    }, 500);

  } catch (error) {
    ElMessage.error('支付流程异常: ' + error.message);
    paymentStatus.value = 'failed';
  } finally {
    loading.value = false;
    isPaying.value = false;
  }
};

// 轮询订单状态
const startPaymentPolling = () => {
  let attempts = 0;
  const maxAttempts = 30; // 最多尝试30次（约3分钟）
  
  paymentPolling.value = setInterval(async () => {
    attempts++;
    
    try {
      const response = await axios.get(`${API_BASE_URL}/order/status`, {
        params: { orderid: orderId.value }
      });
      
      const status = response.data;
      
      if (status === 2) { // 2表示已支付
        clearInterval(paymentPolling.value);
        paymentStatus.value = 'success';
  
      // 修改为跳转到订单详情页
      setTimeout(() => {
        router.push({
          path: `/order/detail/${orderId.value}`,
          // query: {
          //   merchantId: merchant.value.merchantId,
          //   merchantName: merchant.value.name,
          //   merchantAvatar: merchant.value.avatar_path,
          //   deliveryFee: deliveryFee.value,
          //   selectedFoods: JSON.stringify(selectedFoods.value),
          //   address: selectedAddress.value.address,
          //   phone: selectedAddress.value.phone
          // }
        });
      }, 1500); // 1.5秒后跳转
    } else if (status !== 1 || attempts >= maxAttempts) { 
        // 状态不是待支付或超过最大尝试次数
        clearInterval(paymentPolling.value);
        paymentStatus.value = 'failed';
      }
      
    } catch (error) {
      console.error('轮询订单状态失败:', error);
      if (attempts >= maxAttempts) {
        clearInterval(paymentPolling.value);
        paymentStatus.value = 'failed';
      }
    }
  }, 6000); // 每6秒轮询一次
};

// 处理支付结果
const handlePaymentResult = () => {
  showPaymentDialog.value = false;
  if (paymentStatus.value === 'success') {
    router.push('/Msite');
  }
};

// 清理轮询
onUnmounted(() => {
  if (paymentPolling.value) {
    clearInterval(paymentPolling.value);
  }
});

// 初始化
onMounted(() => {
  if (!selectedFoods.value.length) {
    ElMessage.warning('没有选中商品');
    router.push('/msite');
    return;
  }
  
  // 默认使用当前地址
  selectCurrentAddress();
  // 加载历史地址
  fetchAddressList();
});
</script>

<style scoped>
.order-confirm-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.order-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 50px;
  border-bottom: 1px solid #eee;
}

.header-back {
  margin-right: 10px;
  cursor: pointer;
  font-size: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.address-section {
  background-color: #fff;
  padding: 15px;
  margin: 10px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: all 0.3s;
}

.address-section:hover {
  background-color: #f9f9f9;
}

.address-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.address-info .el-icon {
  font-size: 20px;
  color: #ff5339;
  margin-right: 10px;
}

.address-details {
  flex: 1;
}

.receiver {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 5px;
}

.receiver span:first-child {
  margin-right: 15px;
  font-weight: bold;
}

.address {
  font-size: 14px;
  color: #666;
}

/* 地址对话框样式 */
.address-list {
  max-height: 60vh;
  overflow-y: auto;
}

.current-address-title,
.history-address-title {
  font-size: 14px;
  color: #999;
  margin: 10px 0 5px 0;
  padding-left: 5px;
}

.address-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  background-color: #f0f0f0;
}

.address-item.selected {
  border: 1px solid #409eff;
  background-color: #ecf5ff;
}

.address-item.current {
  background-color: #e6f7ff;
}

.address-content {
  flex: 1;
}

.address-text {
  color: #666;
  font-size: 14px;
  margin-top: 5px;
}

.add-address {
  margin-top: 20px;
  padding: 15px;
  border-top: 1px solid #eee;
}

/* 订单商品列表 */
.order-items {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
}

.merchant-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
}

.item-list {
  margin-top: 10px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.item-name {
  flex: 1;
  font-size: 15px;
}

.item-quantity {
  width: 50px;
  text-align: center;
  color: #666;
}

.item-price {
  width: 80px;
  text-align: right;
  font-weight: bold;
}

/* 订单费用明细 */
.order-summary {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.summary-row.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f5f5f5;
  font-size: 16px;
}

.total-price {
  color: #ff5339;
  font-weight: bold;
  font-size: 18px;
}

/* 支付方式 */
.payment-method {
  background-color: #fff;
  margin: 10px;
  border-radius: 8px;
  padding: 15px;
}

.payment-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.payment-option {
  display: flex;
  align-items: center;
}

.alipay-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.payment-option span {
  flex: 1;
}

/* 提交订单按钮 */
.submit-order {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.pay-btn {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
  border-radius: 25px;
}

.pay-btn:disabled {
  background-color: #ccc;
  border-color: #ccc;
  cursor: not-allowed;
}

/* 支付状态样式 */
.payment-status {
  text-align: center;
  padding: 20px;
}

.loading-icon {
  font-size: 50px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.success-icon {
  font-size: 50px;
  color: #67C23A;
}

.error-icon {
  font-size: 50px;
  color: #F56C6C;
}

.status-text {
  margin: 20px 0;
  font-size: 18px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>